package com.caijb.redisdemo.monitor;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 测试普罗米修斯的功能
 * @author caijb
 * @version 1.0
 * @data 2025/11/7 01:36
 */

@Component
public class TestMonitor {

    @Resource
    private MeterRegistry meterRegistry;

    // 缓存已创建的指标，避免重复创建（按指标类型分离缓存）

    // 请求总数
    private final ConcurrentMap<String, Counter> requestCountersCache = new ConcurrentHashMap<>();
    // 错误总数
    private final ConcurrentMap<String, Counter> errorCountersCache = new ConcurrentHashMap<>();
    // 请求成功总数
    private final ConcurrentMap<String, Counter> successCountersCache = new ConcurrentHashMap<>();
    // 响应时间
    private final ConcurrentMap<String, Timer> responseTimersCache = new ConcurrentHashMap<>();

    /**
     * 记录Token消耗
     */
    public void successCount(String userId, String appId, String modelName,
                             long tokenCount) {
        String key = String.format("%s_%s_%s", userId, appId, modelName);
        Counter counter = successCountersCache.computeIfAbsent(key, k ->
                Counter.builder("ai_model_tokens_total")
                        .description("AI模型Token消耗总数")
                        .tag("user_id", userId)
                        .tag("app_id", appId)
                        .tag("model_name", modelName)
                        .register(meterRegistry)
        );
        counter.increment(tokenCount);
    }

    /**
     * 记录响应时间
     * @param userId
     * @param appId
     * @param modelName
     * @param duration
     */
    public void recordResponseTime(String userId, String appId, String modelName, Duration duration) {
        String key = String.format("%s_%s_%s", userId, appId, modelName);
        Timer timer = responseTimersCache.computeIfAbsent(key, k ->
                Timer.builder("ai_model_response_duration_seconds")
                        .description("AI模型响应时间")
                        .tag("user_id", userId)
                        .tag("app_id", appId)
                        .tag("model_name", modelName)
                        .register(meterRegistry)
        );
        timer.record(duration);
    }
}
